<template>
  <div class="file-center">
    <div class="header">
      <div class="header-action clearfix">
        <ul class="action-list l">
          <li class="action-item">
            <el-dropdown>
              <div class="basebtn">
                <button :disabled="showEditor !== 0" :class="{'disable': showEditor !== 0 }" class="lan" @click="clickUploadFile">上传文件</button>
              </div>
              <el-dropdown-menu slot="dropdown" v-if="showEditor === 0">
                <el-dropdown-item>
                  <div @click="clickUploadFile">上传文件</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="isSupportDir">
                  <div @click="clickUploadFolder">上传文件夹</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </li>
          <li class="action-item"><div class="basebtn"><button :disabled="showEditor !== 0" :class="{'disable': showEditor !== 0}" class="lan" @click="dialog.createFileFolder=true">新建文件夹</button></div></li>
        </ul>
        <ul class="action-list action-list-right r">
          <li class="action-item">
            <div class="basebtn">
              <button :disabled="!multipleSelection.length || showEditor !== 0" :class="{'disable' : !multipleSelection.length || showEditor !== 0}" @click="deleteFile">删除</button>
            </div>
          </li>
          <li class="action-item">
            <div>
              <!-- <span><a :class="{'disable' : !multipleSelection.length || showEditor}" class="download-click" :href="!multipleSelection.length || showEditor ? 'javascript:void(0)' : downloadUrl">下载</a></span> -->
              <span><a :class="{'disable' : !multipleSelection.length || showEditor !== 0}" class="download-click" @click="_downLoadFile">下载</a></span>
            </div>
          </li>
          <li class="action-item">
            <div class="basebtn">
              <button :disabled="!multipleSelection.length || multipleSelection.length !== 1  || showEditor !== 0" :class="{'disable' : !multipleSelection.length || multipleSelection.length !== 1 || showEditor !== 0 }" @click="clickRename">重命名</button>
            </div>
          </li>
          <li class="action-item">
            <div class="basebtn">
              <button :disabled="!multipleSelection.length || showEditor !== 0" :class="{'disable' : !multipleSelection.length || showEditor !== 0}" @click="clickCopy">复制</button>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="content-box">
      <div class="content">
        <div class="filepath-header">
          <img class="file-icon" src="@/common/image/icon/folder.png">
          <div class="breadcrumb" v-if="curFilePath === '/'">
            <span class="file-path" @click="clickFilePath('/')">/userhome</span>
          </div>
          <div class="breadcrumb" v-else>
            <span class="file-path" @click="clickFilePath('/')">/userhome</span>
            <span class="file-path" v-for="(item, key) in filePath.slice(1)" :key="key" @click="clickFilePath(item, key)">/{{item}}</span>
          </div>
        </div>
        <div class="file-table" v-show="!showEditor">
          <el-table
            ref="multipleTable"
            :data="fileList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :header-row-class-name="handleTableHeaderclass">
            <el-table-column type="selection" width="40" :selectable="selectable"></el-table-column>
            <el-table-column
              label="文件/文件夹名称"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <div class="table-link" @click="clickTableRow(scope.row)">
                  <i :class="{'file-pic': scope.row.isImg, 'file-icon': !scope.row.directory && !scope.row.isImg, 'folder-icon': scope.row.directory}"></i>
                  <span>{{ scope.row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="修改日期"
              width="200">
              <template slot-scope="scope">
                <span>{{ new Date(scope.row.updateTime).Format("yyyy-MM-dd hh:mm:ss") }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="size"
              label="大小"
              width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.size ? scope.row.size : '--' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="basePagenate">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-size="pageSize"
              :current-page="pageNumber"
              :total="totalPage"
              layout="prev, pager, next">
            </el-pagination>
          </div>
        </div>
        <div v-show="showEditor === 1" class="editor-container">
          <!-- <div class="editor-header header-editor-box">
            <span>{{curEditFile.fileName}}</span>
            <div v-show="showEdit" class="action r action-right">
              <i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span>
            </div>
            <div v-show="showEdit" class="action r" @click="doEdit">
              <span><i class="el-icon-edit-outline"></i><span class="action-span-hover">编辑</span></span>
            </div>
            <div v-show="!showEdit" class="r">
              <span class="action action-right"><i class="icon-save" /><span  class="action-span-hover" @click="doEditSave(0)">保存</span><i class="icon-cancle" /><span class="action-span-hover" @click="doEditCancle">取消</span></span>
            </div>
          </div> -->
          <div class="header-editor-box">
            <span class="header-editor-left-text">{{curEditFile.fileName}}</span>
            <div class="header-right">
              <span class="header-right-edit" v-if="showEdit" @click="doEdit"><i class="el-icon-edit-outline"></i><span class="">编辑</span></span>
              <span class="header-right-save" v-if="!showEdit">
                <el-button class="icon-cancle" @click="doEditCancle">取消</el-button>
                <el-button class="icon-save" type="primary" @click="doEditSave(0)">保存</el-button>
              </span>
            </div>
          </div>
          <div class="code-eidtor">
            <div ref="container" id="container" style="width:100%;height:700px;border:1px solid #ddd"></div>
          </div>
        </div>
        <div v-show="showEditor === 2" class="editor-container">
          <div class="editor-header">
            <span>{{curEditFile.fileName}}</span>
            <div v-show="!showMDEdit" class="action r action-right"><i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span></div>
            <div v-show="!showMDEdit" class="action r" @click="doMDEdit"><span><i class="el-icon-edit-outline"></i><span class="action-span-hover">编辑</span></span></div>
            <div v-show="showMDEdit" class="r">
              <span class="action action-right"><i class="icon-save" /><span  class="action-span-hover" @click="doEditSave(1)">保存</span><i class="icon-cancle" /><span class="action-span-hover" @click="doMDEditCancle">取消</span></span>
            </div>
          </div>
          <viewer
            v-show="!showMDEdit"
            :value="markdownData"
            height="500px"
            class="md-content"
          />
          <editor
            v-show="showMDEdit"
            ref="mdEditor"
            v-model="markdownData"
            :options="editorOptions"
            previewStyle="vertical"
            height="500px"
          />
        </div>
      </div>
    </div>
    <!-- 创建文件夹 -->
    <el-dialog
      title="创建文件夹"
      :visible.sync="dialog.createFileFolder"
      :pos="'center'"
      :width="'440px'"
      @close="resetForm('cffForm')">
      <el-form :model="createFileFolderForm" :rules="rulesCreateFolder" ref="cffForm" @submit.native.prevent>
        <el-form-item label="文件夹名称：" :label-width="'120px'" prop="name">
          <el-input @keyup.enter.native="submitForm('cffForm')" v-model="createFileFolderForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="submitForm('cffForm')" class="dialog-button lan">确 定</button>
          <button @click="dialog.createFileFolder=false" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <!-- 重命名 -->
    <el-dialog
      title="重命名"
      :visible.sync="dialog.rename"
      :pos="'center'"
      :width="'440px'"
      @close="resetForm('renameForm')">
      <el-form :model="renameForm" :rules="rulesRename" ref="renameForm" @submit.native.prevent>
        <el-form-item label="名称：" :label-width="'80px'" prop="name">
          <el-input @keyup.enter.native="submitForm('renameForm')" v-model="renameForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="submitForm('renameForm')" class="dialog-button lan">确 定</button>
          <button @click="dialog.rename=false" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <!-- 上传列表 -->
    <el-dialog
      title="上传列表"
      :visible.sync="dialog.uploadList"
      :close-on-click-modal="false"
      @close="closeUploadDialog"
      :pos="'center'"
      :width="'600px'">
      <div class="file-panel">
        <h2>文件列表</h2>
        <div class="file-list">
          <ul class="file-item" :class="`file-${file.id}`" v-for="(file, index) in uploadFileList" :key="index">
            <li class="file-type"></li>
            <li class="file-name">{{file.name}}</li>
            <li class="file-size">{{fileSize(file.size)}}</li>
            <li class="file-status">待上传</li>
            <li class="progress"></li>
          </ul>
          <div class="no-file" v-if="!uploadFileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button type="primary" @click="startUpload()" class="dialog-button lan">开始上传</button>
          <button @click="cancleUpload" class="dialog-button active last">取 消</button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="图片浏览"
      :visible.sync="dialog.picPreview"
      :pos="'center'"
      width="40%">
      <div class="file-panel picPreview">
        <img :src="curPicPreView" />
      </div>
      <!-- <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button @click="dialog.picPreview=false" class="dialog-button active last">关 闭</button>
        </div>
      </div> -->
    </el-dialog>
    <!-- 上传文件组件 -->
    <div id="filePicker" class="upload-location">上传文件</div>
    <vue-upload
      ref="uploader"
      uploadButton="#filePicker"
      url="/gateway/fileCenter/api/file/upload?type=1"
      multiple
      :headers="uploadHeader"
      @fileChange="fileChange"
      :fileSingleSizeLimit="fileSingleSize"
      @uploadStart="onUploadStart"
      @progress="onProgress"
      @completeAll="onAllSuccess"
      @error="onError"
    ></vue-upload>
  </div>
</template>

<script>
import axios from 'axios'
import store from '../../store.js'
import { apiGetFileList, apiCreateFileFolder, apiDeleteFile, apiRename, apiCopy } from '@/api/filecenter'
import vueUpload from '@/base/vue-upload'
import { mapMutations, mapGetters } from 'vuex'
import * as monaco from 'monaco-editor'
import 'tui-editor/dist/tui-editor.css'
import 'tui-editor/dist/tui-editor-contents.css'
import 'codemirror/lib/codemirror.css'
import { Editor, Viewer } from '@toast-ui/vue-editor'
import { verifyFileType } from '@/common/js/utils'
import qs from 'qs'

const WebUploaderObj = window.WebUploader
// 表单校验-name-长度校验
var validateName = (rule, value, callback) => {
  if (value.length > 30) {
    callback(new Error('名称长度须在1到30个字符之间'))
  } else {
    callback()
  }
}
export default {
  data () {
    return {
      editor: '',
      // 总页数
      totalPage: 0,
      // 每页条数
      pageSize: 10,
      // 当前页
      pageNumber: 1,
      // 文件总数
      total: 13,
      // Table选择项
      multipleSelection: [],
      // 文件列表
      fileList: [],
      // 上传文件列表
      uploadFileList: [],
      // 文件路径
      filePath: ['/'],
      // 当前文件路径
      curFilePath: '/',
      // 弹窗显隐
      dialog: {
        createFileFolder: false,
        rename: false,
        uploadList: false,
        picPreview: false
      },
      // 弹窗表单-创建文件夹
      createFileFolderForm: {
        name: ''
      },
      // 弹窗表单-重命名
      renameForm: {
        name: ''
      },
      // 表单验证规则-创建文件夹
      rulesCreateFolder: {
        name: [
          { required: true, message: '请输入文件名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ]
      },
      // 表单验证规则-重命名
      rulesRename: {
        name: [
          { required: true, message: '请输入文件名称', trigger: 'blur' }
        ]
      },
      // 文件内容
      fileContent: '',
      // 用户ID（临时）
      userId: '',
      // 显示编辑器
      showEditor: 0,
      // 编辑器显示编辑按钮
      showEdit: true,
      showMDEdit: false,
      // 编辑器是否可编辑
      readOnly: true,
      // 当前编辑文件
      curEditFile: '',
      // 当前浏览图片
      curPicPreView: '',
      isSupportDir: true,
      // 上传文件大小限制
      fileSingleSize: 500 * 1024 * 1024,
      flag: false,
      // md文件内容
      markdownData: '',
      // 文件内容 原始
      fileContentOriginal: '',
      editorOptions: {
        hideModeSwitch: true
      }
    }
  },
  methods: {
    // 点击编辑
    doEdit () {
      this.showEdit = false
      this.editor.updateOptions({ readOnly: false })
    },
    // 点击MarkDown编辑
    doMDEdit () {
      this.showMDEdit = true
      this.$nextTick(() => {
        this.$refs.mdEditor.invoke('setValue', this.markdownData)
        this.$refs.mdEditor.invoke('scrollTop', 1)
      })
    },
    doCancle () {
      this.showEditor = 0
    },
    /*
      description:点击编辑保存
      type: 0 -> tui编辑器保存；1 -> markdown编辑器保存
    */
    doEditSave (type = 0) {
      let blob = ''
      if (type === 0) {
        blob = new Blob([this.editor.getValue()], { type: 'application/octet-stream' })
      } else {
        blob = new Blob([this.$refs.mdEditor.invoke('getValue')], { type: 'text/plain' })
      }
      let fd = new FormData()
      fd.append('dir', this.curFilePath)
      fd.append('name', this.curEditFile.fileName)
      fd.append('file', blob, this.curEditFile.fileName)
      let url = `/gateway/fileCenter/api/file/upload?type=1`
      axios({
        method: 'post',
        url: url,
        data: fd
      }).then(res => {
        this.$message({ message: '保存成功', showClose: true, type: 'success' })
        this.showEditor = 0
        this.showMDEdit = false
        this._getFileList(this.curFilePath)
      })
    },
    // 点击编辑取消
    doEditCancle () {
      this.editor.setValue(this.fileContent)
      this.showEdit = true
      this.editor.updateOptions({ readOnly: true })
    },
    doMDEditCancle () {
      this.$refs.mdEditor.invoke('setValue', this.fileContentOriginal)
      this.showMDEdit = false
    },
    // Table禁用勾选框
    selectable (row) {
      return !row.symbolicLink
    },
    // 点击上传文件-选择文件
    clickUploadFile () {
      this.flag = false
      this.uploadFileList = []
      document.getElementById('filePicker').getElementsByTagName('input')[0].removeAttribute('webkitdirectory')
      document.getElementById('filePicker').getElementsByTagName('label')[0].click()
    },
    // 点击上传文件-选择文件夹
    clickUploadFolder () {
      this.flag = false
      this.uploadFileList = []
      document.getElementById('filePicker').getElementsByTagName('input')[0].setAttribute('webkitdirectory', '')
      document.getElementById('filePicker').getElementsByTagName('label')[0].click()
    },
    // 获取文件大小
    fileSize (size) {
      return WebUploaderObj.Base.formatSize(size)
    },
    // 上传错误
    onError (msg) {
      this.dialog.uploadList = false
      this.flag = true
      this.$message({ message: msg, showClose: true, type: 'warning' })
    },
    // 开始上传
    startUpload () {
      this.resume()
    },
    cancleUpload () {
      this.dialog.uploadList = false
      this.uploader.reset()
    },
    closeUploadDialog () {
      this.uploader.reset()
    },
    fileChange (file) {
      if (!this.flag) {
        this.dialog.uploadList = true
        this.uploadFileList.push(file)
      }
    },
    onUploadStart (file) {
      let dir = ''
      let source = file.source.source
      if (source.webkitRelativePath) {
        let separator = this.curFilePath === '/' ? '' : '/'
        dir = this.curFilePath + separator + source.webkitRelativePath.slice(0, source.webkitRelativePath.lastIndexOf('/' + source.name))
      } else {
        dir = this.curFilePath
      }
      let formData = {
        'dir': dir,
        'userId': this.userId,
        'name': source.name
      }
      this.uploader.uploader.options.formData = formData
    },
    // uploadBeforeSend (obj, file, headers) {
    //   console.log(headers)
    // },
    onProgress (file, percent) {
      $(`.file-${file.id} .progress`).css('width', percent * 100 + '%')
      $(`.file-${file.id} .file-status`).html((percent * 100).toFixed(2) + '%')
    },
    onSuccess (file, response) {
      this.dialog.uploadList = false
      this._getFileList(this.curFilePath)
    },
    onAllSuccess () {
      this.dialog.uploadList = false
      this._getFileList(this.curFilePath)
    },
    resume (file) {
      this.uploader.upload(file)
    },
    // Table多选操作
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.pageNumber = 1
      this._getFileList(this.curFilePath)
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      this._getFileList(this.curFilePath)
    },
    // 表单提交(cffForm：创建文件夹;renameForm：重命名)
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === 'cffForm') {
            this._createFileFolder()
            this.dialog.createFileFolder = false
          } else if (formName === 'renameForm') {
            this._rename()
            this.dialog.rename = false
          }
          this.resetForm(formName)
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 点击Table列
    clickTableRow (row) {
      this.showEdit = true
      if (row.symbolicLink) {
        return false
      } else {
        if (row.directory) {
          this.goToFolder(row.fileName)
          this.showEditor = 0
        } else if (row.isImg) {
          this.dialog.picPreview = true
          this._previewImg2(row).then(res => {
            this.curPicPreView = URL.createObjectURL(res)
          })
        } else {
          let fileType = row.fileName.replace(/.+\./, '')
          if (fileType === 'md') {
            this.curEditFile = row
            this.fileContent = ''
            this._getFileContent(row, true)
            this.showEditor = 2
          } else if (verifyFileType(fileType)) {
            this.curEditFile = row
            this.fileContent = ''
            this._getFileContent(row)
            this.showEditor = 1
          } else {
            this.$message({ message: '暂不支持该文件类型预览', showClose: true, type: 'warning' })
          }
        }
      }
    },
    // 点击文件夹
    goToFolder (dir) {
      this.pageNumber = 1
      if (this.curFilePath === '/') {
        this.curFilePath = `/${dir}`
      } else {
        this.curFilePath = `${this.curFilePath}/${dir}`
      }
      this.filePath.push(dir)
      this._getFileList(this.curFilePath)
    },
    // 删除文件或文件夹
    deleteFile () {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._deleteFile()
      })
    },
    // 点击重命名
    clickRename () {
      this.dialog.rename = true
      this.renameForm.name = this.multipleSelection[0].fileName
    },
    // 点击复制
    clickCopy () {
      this._copy()
    },
    // 点击文件路径
    clickFilePath (val, key) {
      if (this.showEditor !== 0) {
        this.showEditor = 0
        this.showMDEdit = false
        this.$router.push({ path: '/filecenter' })
      }
      this.pageNumber = 1
      if (val === '/') {
        this.curFilePath = '/'
        this.filePath = ['/']
        this._getFileList('/')
      } else {
        let path = ''
        let pathArr = this.filePath.slice(0, key + 2)
        this.filePath = pathArr
        pathArr.map((item, index) => {
          if (index === 0) {
            path = item
          } else if (index === 1) {
            path = path + item
          } else {
            path = `${path}/${item}`
          }
        })
        this.curFilePath = path
        this._getFileList(path)
      }
    },
    // 浏览器检测input是否具有webkitdirectory属性
    isInputDirSupported () {
      let tmpInput = document.createElement('input')
      if ('webkitdirectory' in tmpInput || 'mozdirectory' in tmpInput || 'odirectory' in tmpInput || 'msdirectory' in tmpInput || 'directory' in tmpInput) {
        return true
      } else {
        return false
      }
    },
    handleTableHeaderclass () {
      return 'table-head-th'
    },
    /*
      -----接口调用-----
    */
    // 查询文件列表
    _getFileList (path) {
      let para = `?type=1&dir=${path}&pageNumber=${this.pageNumber}&pageSize=${this.pageSize}`
      apiGetFileList(para).then(res => {
        if (res.message.code === 0) {
          this.totalPage = res.data.totalCount
          this.fileList = res.data.fileList
          // 判断是否是图片
          let imgExt = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
          this.fileList && this.fileList.forEach(el => {
            let isImg = imgExt.contain(el.fileName.extension())
            el.isImg = isImg
            if (isImg) {
              let preOpt = {}
              let separator = this.curFilePath === '/' ? '' : '/'
              preOpt.src = `/gateway/fileCenter/api/file/preview?type=1&path=${this.curFilePath + separator + el.fileName}`
              el.preOpt = preOpt
            }
          })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 创建文件夹
    _createFileFolder () {
      let path = ''
      if (this.curFilePath === '/') {
        path = `/${this.createFileFolderForm.name}`
      } else {
        path = `${this.curFilePath}/${this.createFileFolderForm.name}`
      }
      let para = qs.stringify({
        type: 1,
        dir: path
      })
      apiCreateFileFolder(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '创建文件夹成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else if (res.message.code === 10000) {
          this.$message({ message: '文件夹已存在，请换个名字试试。', showClose: true, type: 'warning' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 删除文件或文件夹
    _deleteFile () {
      let dirs = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map(item => {
        dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
      })
      let para = `?type=1&${dirs}`
      apiDeleteFile(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '删除文件成功', showClose: true, type: 'success' })
          this.pageNumber = this.pageNumber - 1
          this._getFileList(this.curFilePath)
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 重命名文件或文件夹
    _rename () {
      let para = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      para = `?type=1&dir=${this.curFilePath + separator + this.multipleSelection[0].fileName}&newDir=${this.curFilePath + separator + this.renameForm.name}`
      apiRename(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '重命名成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else if (res.message.code === 10000) {
          this.$message({ message: '文件或文件夹已存在，请换个名字试试。', showClose: true, type: 'warning' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 复制
    _copy () {
      let dirs = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map(item => {
        dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
      })
      let para = `?type=1&${dirs}`
      apiCopy(para).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '复制成功', showClose: true, type: 'success' })
          this._getFileList(this.curFilePath)
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 下载文件
    _downLoadFile () {
      if (this.multipleSelection.length === 0) {
        return false
      }
      let dirs = ''
      const separator = this.curFilePath === '/' ? '' : '/'
      let fileName = ''
      this.multipleSelection.map((item, index) => {
        if (index === 0) {
          dirs = 'dirs=' + this.curFilePath + separator + item.fileName
        } else {
          dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
        }
      })
      if (this.multipleSelection.length === 1 && !this.multipleSelection[0].directory) {
        fileName = this.multipleSelection[0].fileName
      } else {
        fileName = 'package.zip'
      }
      const fileUrl = `/gateway/fileCenter/api/file/download?type=1&${dirs}`
      axios.get(fileUrl, {
        responseType: 'arraybuffer'
      }).then(res => {
        const fileContent = res.data
        const blob = new Blob([fileContent], { type: 'application/octet-stream' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(blob, fileName)
        } else {
          // 创建新的URL表示指定的File对象或者Blob对象
          const URL = window.URL || window.webkitURL
          const aTag = document.createElement('a')
          aTag.style = 'display: none'
          aTag.download = fileName
          aTag.href = URL.createObjectURL(blob)
          document.body.appendChild(aTag)
          aTag.click()
          document.body.removeChild(aTag)
          URL.revokeObjectURL(blob)
        }
        // 下载完成，清空Table用户选择
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection()
      })
    },
    // 下载文件内容
    _getFileContent (row, isMDFile = false) {
      let separator = this.curFilePath === '/' ? '' : '/'
      let fileUrl = `/gateway/fileCenter/api/file/preview?type=1&path=${this.curFilePath + separator + row.fileName}`
      axios({
        method: 'get',
        url: fileUrl
      }).then(res => {
        if (!isMDFile) {
          this.fileContent = res.data
          this.$refs.container.innerHTML = ''
          this.editor = monaco.editor.create(document.getElementById('container'), {
            value: '',
            language: 'python',
            readOnly: true
          })
          if (typeof this.fileContent === 'object') {
            this.fileContent = res.request.response
            this.editor.setValue(this.fileContent)
          } else {
            this.editor.setValue(String(this.fileContent))
          }
        } else {
          if (res.data === '') {
            this.showEditor = 0
          } else {
            this.showEditor = 2
            this.markdownData = res.data
            this.fileContentOriginal = res.data
          }
        }
      })
    },
    // 预览图片
    _previewImg (row) {
      let separator = this.curFilePath === '/' ? '' : '/'
      let fileUrl = `/gateway/fileCenter/api/file/preview?type=1&path=${this.curFilePath + separator + row.fileName}`
      // let reader = new FileReader()
      axios({
        method: 'get',
        url: fileUrl
      }).then(res => {
        // let blob = new Blob([res.data], { type: 'image/jpeg' })
        // reader.readAsDataURL(blob)
        let img = document.createElement('img')
        img.src = res.data
        document.body.appendChild(img)
      })
      // console.log(reader)
      // reader.onload = (e) => {
      //   let img = document.createElement('img')
      //   img.src = e.target.result
      //   console.log(e.target.result)
      //   document.body.appendChild(img)
      // }
    },
    _previewImg2 (row) {
      let separator = this.curFilePath === '/' ? '' : '/'
      let fileUrl = `/gateway/fileCenter/api/file/preview?type=1&path=${this.curFilePath + separator + row.fileName}`
      return axios({
        method: 'get',
        url: fileUrl,
        responseType: 'blob',
        emulateJSON: true
      }).then(res => {
        return Promise.resolve(res.data)
      })
    },
    ...mapMutations({
      storeCurEditFile: 'SET_CUR_EDIT_FILE'
    })
  },
  mounted () {
    if (this.$route.path === '/filecenter/editor') {
      this.showEditor = 0
    }
    if (this.$route.query.userId) {
      this.userId = this.$route.query.userId
    } else {
      this.userId = store.state.userInfo.userId
    }
    this.isSupportDir = this.isInputDirSupported()
    if (this.storeFilePath.curFilePath) {
      this.curFilePath = this.storeFilePath.curFilePath
      this.filePath = this.storeFilePath.filePath
      this.storeCurEditFile('')
    }
    this._getFileList(this.curFilePath)
  },
  computed: {
    ...mapGetters({
      storeFilePath: 'curEditFile'
    }),
    // WebUploader对象
    uploader () {
      return this.$refs.uploader
    },
    // 文件下载链接
    downloadUrl () {
      let dirs = ''
      let separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map(item => {
        dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
      })
      let url = `/gateway/fileCenter/api/file/download?type=1&${dirs}`
      return url
    },
    uploadHeader: () => {
      let obj = {
        token: store.state.userInfo.token,
        bitaToken: store.state.userInfo.bitaToken,
        userId: store.state.userInfo.userId
      }
      return obj
    }
  },
  components: {
    vueUpload,
    'editor': Editor,
    'viewer': Viewer
  }
}
</script>

<style lang="stylus">
@import "../../common/stylus/mixin"
@import "../../common/stylus/base"
@import "../../common/stylus/core/filecenter"
@import "../../common/stylus/header_editor_box"

.file-center
  .header
    height 121px
    background #F4F7F8
    .header-action
      height 100%
      max-width 1162px
      margin 0 auto
      display flex
      align-items center
      justify-content space-between
      .action-list
        display flex
        align-items center
        .action-item
          display flex
          align-items center
          .last-button
            margin-right 0
          .download-click
            font-size 12px
            line-height 28px
            padding 0 15px
            margin 0 10px 0 0
            float left
            border 1px solid $color-border
            border-radius 4px
            color #333
            outline none
            cursor pointer
            text-decoration none
            background #ffffff
            &:hover
              color $color-lan
            &.disable
              color $color-border
              cursor not-allowed
      .action-list-right
        margin-left auto
  .content-box
    width 100%
    position relative
    margin 0 auto
    max-width 1162px
    padding 20px 0
    .content
      background #ffffff
      border-radius 5px
      .filepath-header
        height 20px
        line-height 20px
        display flex
        align-items center
        padding-left 10px
        margin-bottom 20px
        .file-icon
          width 16px
          height 16px
          display inline-block
        .breadcrumb
          display inline-block
          font-weight 600
          font-size 14px
          color #2D323B
          padding-left 10px
          .file-path
            cursor pointer
            &:hover
              color: $color-lan
      .file-table
        .table-link
          cursor pointer
          overflow hidden
          text-overflow ellipsis
          white-space nowrap
          >span
            &:hover
              color: $color-lan
        .file-icon
          model(16px,16px,0 11px 0 0)
          background-image url('../../common/image/icon/file.png')
          background-size 16px 16px
          display inline-block
          vertical-align middle
        .folder-icon
          model(16px,16px,0 11px 0 0)
          background-image url('../../common/image/icon/folder.png')
          background-size 16px 16px
          display inline-block
          vertical-align middle
        .file-pic
          model(16px,16px,0 11px 0 0)
          background-image url('../../common/image/icon/file-image.png')
          background-size 16px 16px
          display inline-block
          vertical-align middle
  .editor-container
    margin-top 20px
    .editor-header
      height 40px
      line-height 40px
      background-color #f8f8f8
      border 1px solid #ddd
      border-radius 5px 5px 0 0
      font-size 14px
      border-bottom none
      font-weight 500
      padding 0 10px
      >span
        padding 0 10px
      .action
        // padding-right 10px
        color #4285f4
        cursor pointer
        font-size 12px
      .action-right
        display flex
        align-items center
      .icon-cancle
        display inline-block
        margin-left 10px
        width 12px
        height 12px
        margin-right 3px
        background url('../../common/image/icon/edit-cancle.png')
        background-size 12px 12px
      .icon-save
        display inline-block
        width 12px
        height 12px
        margin-right 3px
        background url('../../common/image/icon/save.png')
        background-size 12px 12px
      span
        font-size 12px
        color #8F9498
        letter-spacing 0
        >i
          padding-right 3px
        &.action-span-hover:hover
          color #5e6061
    .code-eidtor
      margin-bottom 10px
      line-height 24px
    .md-content
      padding 20px
      width 100%
      border 1px solid #ddd
  .dialog-button
    float none
  .upload-location
    display none
  .picPreview
    display flex
    justify-content center
    box-shadow none
    img
      width 90%
      height 90%
  .table-head-th
    background #F1F8FF
    font-weight 600
    font-size 14px
    color #4A4A4A
  .tui-editor-defaultUI
    width 100%
</style>
